import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router';
import { LOGIN_COOKIE_KEY, ROUTER_TYPE } from '@/constants/index';
import { thyCookie, thyUrl } from '@thyiad/util';

export type RouteProps = RouteRecordRaw & {
    hideInMenu?: boolean;
    children?: RouteProps[];
    title?: string;
    icon?: string;
    roles?: string[];
};

const NoPermission = () => import('./pages/403/index.vue');
const NotFound = () => import('./pages/404/index.vue');
const Login = () => import('./pages/login/index.vue');
const LeftMenuLayout = () => import('./layout/LeftMenuLayout.vue');
const EmptyWrapper = () => import('./layout/EmptyWrapper.vue');
const Dashboard = () => import('./pages/dashboard/index.vue');
const Demo = () => import('./pages/demo/index.vue');
const Table = () => import('./pages/demo/table.vue');

export const menus: RouteProps[] = [
    {
        title: '首页',
        path: '/dashboard',
        component: Dashboard,
        icon: 'el-icon-s-home',
    },
    {
        title: 'demo',
        path: '/demo',
        component: Demo,
        icon: 'el-icon-table-lamp',
        roles: ['admin'],
    },
    {
        title: 'demo1',
        path: '/demo1',
        component: Demo,
        icon: 'el-icon-table-lamp',
        roles: ['admin1'],
    },
    {
        title: '多级菜单',
        path: '/multi',
        icon: 'el-icon-table-lamp',
        roles: ['admin1'],
        component: EmptyWrapper,
        children: [
            {
                title: '列表',
                path: '/multi/userList',
                component: Table,
                icon: 'el-icon-user-solid',
            },
        ],
    },
    {
        path: '*',
        redirect: '/404',
        hideInMenu: true,
    },
];

const routes: RouteProps[] = [
    {
        path: '/403',
        name: '403',
        component: NoPermission,
    },
    {
        path: '/404',
        name: '404',
        component: NotFound,
    },
    {
        path: '/user/login',
        component: Login,
    },
    {
        path: '/',
        component: LeftMenuLayout,
        redirect: '/dashboard',
        children: menus,
    },
];

const router = createRouter({
    history: ROUTER_TYPE === 'history' ? createWebHistory() : createWebHashHistory(),
    routes,
    // scrollBehavior(to, from, savedPosition) {
    //   return { top: 0 }
    // },
});

router.beforeEach((to, from, next) => {
    // 非登录页面检查一下cookie，没有就去登录
    if (to.path !== '/user/login') {
        const hasCookie = !!thyCookie.get(LOGIN_COOKIE_KEY);
        if (!hasCookie) {
            next({ replace: true, path: '/user/login' });
            return;
        }
    }

    next();
});

export default router;
